package com.cennavi.list;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cennavi.dbs.MongoPool;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;

import net.sf.json.JSONObject;

public class DataStatResults extends HttpServlet {

 
	/**
	 * 
	 */
	private static final long serialVersionUID = -4841720616795376255L;

	public DataStatResults() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods",
				"POST, GET, OPTIONS, DELETE,PUT");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		try {

			String jsonStr = request.getParameter("request");
			jsonStr = new String(jsonStr.getBytes("ISO-8859-1"),"UTF-8");
			JSONObject json = JSONObject.fromObject(jsonStr);

			String table = "data_stat_results";

			int startPage = json.getInt("start_page");

			int pageSize = json.getInt("page_size");

			DBCollection collection = MongoPool.getDB().getCollection(table);
			
			BasicDBObject query = new BasicDBObject();
			
			if (json.containsKey("instruction_id") && json.getString("instruction_id").length()>0)
				
			{
//				queryJSON.put("instruction_id", "%"+json.getString("instruction_id")+"%");
				Pattern pattern = Pattern.compile(json.getString("instruction_id"), Pattern.CASE_INSENSITIVE);
		        
		        query.put("instruction_id",pattern);
			}

			DBCursor cursor = collection.find(query,
					(DBObject) JSON.parse("{'_id':" + 0 + "}"));

			int totalCount = (int) cursor.count();

			cursor.skip((startPage - 1) * pageSize);

			cursor.limit(pageSize);

			out.println("{\"error_code\":0,\"error_msg\":null,\"content\":{\"total_count\":"
					+ totalCount + ",\"data\":");

			out.println("[");

			boolean flag = false;

			while (cursor.hasNext()) {

				if (!flag) {
					flag = true;
					out.println(cursor.next());
				} else {
					out.println("," + cursor.next());
				}
			}

			out.println("]");

			out.println("}");

			out.println("}");

		} catch (Exception e) {
			out.println("{\"error_code\":-1,\"error_msg\":\"" + e.getMessage()
					+ "\"}");
		} finally {
			out.flush();

			out.close();
		}

	}

	public void init() throws ServletException {
		// Put your code here
	}

}
